package com.android.fragmentdemo.thread2

import org.junit.Test
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveTask

class Demo2 {

    @Test
    fun testForkJoin() {
        val pool = ForkJoinPool()
        val calculatorTask = SumCalculator(1, 10000)
        val result = pool.invoke(calculatorTask)
        println("result:$result")
    }

    class SumCalculator(start: Int, end: Int) : RecursiveTask<Int>() {
        private val mStart = start
        private val mEnd = end
        override fun compute(): Int {
            return if (mEnd - mStart <= 10) {
                //任务足够小,则直接计算结果.
                var sum = 0
                for (i in (mStart..mEnd)) {
                    sum += i
                }
                sum
            } else {
                //否则,分割任务.
                val middle = (mStart + mEnd) / 2
                val calculator0 = SumCalculator(mStart, middle)
                val calculator1 = SumCalculator(middle + 1, mEnd)
                calculator0.fork()//创建子任务并异步执行
                val subResult2 = calculator1.compute()//同步执行另一个子任务
                subResult2 + calculator0.join()//等待子任务完成合并结果
            }
        }
    }
}